package pl.freetimetool.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import pl.freetimetool.domain.Project;
import pl.freetimetool.service.ProjectService;

@Controller
public class ProjectController {

	@Autowired
	ProjectService projectService;

	@RequestMapping(value = "/project/add", method = RequestMethod.GET)
	public ModelAndView add() {
		final ModelAndView mav = new ModelAndView("/project/add");
		mav.addObject("project", new Project());
		return mav;
	}

	@RequestMapping(value = "/project/add", method = RequestMethod.POST)
	public ModelAndView add(@Valid final Project project, final BindingResult result) {
		final ModelAndView mav = new ModelAndView("project/add");

		if (result.hasErrors()) {
			mav.addObject("project", project);
			return mav;
		}
		this.projectService.addNewProject(project);

		mav.setViewName("redirect:/project/showDetails/" + project.getProjectName());
		return mav;
	}

	@RequestMapping(value = "/project/showDetails/{projectName}", method = RequestMethod.GET)
	public ModelAndView details(@PathVariable("projectName") final String projectName) {
		final ModelAndView mav = new ModelAndView("project/showDetails");
		mav.addObject("project", this.projectService.getProject(projectName));

		return mav;
	}

	@RequestMapping(value = "/project/delete", method = RequestMethod.GET)
	public ModelAndView delete() {
		final ModelAndView mav = new ModelAndView("/project/delete");
		mav.addObject("project", new Project());
		return mav;
	}

	@RequestMapping(value = "/project/delete", method = RequestMethod.POST)
	public ModelAndView delete(@Valid final Project project) {
		final ModelAndView mav = new ModelAndView("project/delete");

		if (project != null) {
			this.projectService.removeProject(project.getProjectName());
		}

		mav.setViewName("redirect:/project/deleteConfirmed");
		return mav;
	}

	@RequestMapping(value = "/project/deleteConfirmed", method = RequestMethod.GET)
	public ModelAndView deletionDetails() {
		final ModelAndView mav = new ModelAndView("common/deleteConfirmed");
		mav.addObject("acc", "Project");
		return mav;
	}

	@RequestMapping(value = "/project/showAll", method = RequestMethod.GET)
	public ModelAndView showAll() {
		final ModelAndView mav = new ModelAndView("project/getAll");
		mav.addObject("projects", this.projectService.findAllProjects());
		return mav;
	}
}
